package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.DTO.OrdersDto;
import com.reggie.common.BaseContext;
import com.reggie.common.CustomException;
import com.reggie.common.R;
import com.reggie.entity.*;
import com.reggie.mapper.OrdersMapper;
import com.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.lang.invoke.LambdaConversionException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
//    提交订单
    public R<String> submit(Orders orders) {
//        是哪个用户下的单（在session里有当前用户的id）
//
        Long userId = BaseContext.getCuttendId();
//        然后通过id查询他的购物车信息
//
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
//        因为一个用户有多个商品所有用list
        List<ShoppingCart> catMessage = shoppingCartService.list(lambdaQueryWrapper);
        if (catMessage == null || catMessage.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        //
//        用于查询信息补全 orders表
        User user = userService.getById(userId);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
//        该方法是mb自带的一个id 用于设置订单id的
        long orderId = IdWorker.getId();
//        遍历总金额  这里需要用到订单明细表 因为有份数金额之类的
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetailList = catMessage.stream().map(item -> {
//            通过遍历把每一份菜单都明细保存好
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
//            总金额 把amount乘number然后封装到big对象里面  然后再转换为int格式
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
//
//                然后向订单表插入一条数据
//

        // 设置订单信息
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
//        金额需要从购物车中遍历相加
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
//        拼接 地址信息
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);
//        然后向订单明细表插入一条或多条数据（一个商品一条数据）
//批量插入
        orderDetailService.saveBatch(orderDetailList);
//        最后因为提交了订单 所以购物车清空
//        这一句查询到的是用户id相同的购物车数据  然后把整个数据删除
        shoppingCartService.remove(lambdaQueryWrapper);
//这个是通过用户id执行通过id删除该id的字段（一般都是传一组数据不是一个id）行不通
//        shoppingCartService.removeById(userId);
        return null;
    }

}
